package com.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MyClassLoader extends ClassLoader{
    private final String dir;

    public MyClassLoader(String dir) {
        this.dir = dir;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        File root = new File(dir);
        File target = new File(root, name.replace(".", File.separator) + ".xlass");
        if (!target.exists()) {
            throw new ClassNotFoundException();
        }
        try (FileInputStream fis = new FileInputStream(target)) {
            byte[] raw = fis.readAllBytes();
            return defineClass(name, decode(raw), 0, raw.length);
        } catch (IOException ex) {
            throw new ClassNotFoundException(ex.getMessage());
        }
    }

    private byte[] decode(byte[] raw) {
        for (int i = 0; i < raw.length; ++i) {
            raw[i] ^= 0xff;
        }
        return raw;
    }
}
